package com.example.demo.jpa.org.dao;

import com.example.demo.jpa.config.exception.CustomException;
import com.example.demo.jpa.config.exception.ExceptionResp;
import com.example.demo.jpa.customer.constants.Sex;
import com.example.demo.jpa.customer.domain.Customer;
import com.example.demo.jpa.customer.dto.CustomerDTO;
import com.example.demo.jpa.org.domain.Org;
import com.example.demo.jpa.org.dto.OrgCommand;
import com.example.demo.jpa.org.dto.OrgDto;
import com.example.demo.jpa.org.repo.OrgRepository;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Component
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrgDao {
    @Autowired
    OrgRepository orgRepository;

    public OrgDto findOrgByID(long id) {
        Org org1 = orgRepository.findById(id);
        if (Objects.isNull(org1)) {
            throw new CustomException(ExceptionResp.ORG_NOT_FOUND, "Org not found");
        }
        return new OrgDto(org1.getId(), org1.getName(), org1.getAddress());
    }

    @Transactional
    public void deleteById(long id) {
        Org org1 = orgRepository.findById(id);
        if (Objects.isNull(org1)) {
            throw new CustomException(ExceptionResp.ORG_NOT_FOUND, "Org not found");
        } else {
            orgRepository.deleteById(id);
        }
    }

    @Transactional
    public OrgDto createOrg(OrgCommand orgCommand) {
        Org org = new Org(orgCommand.getName(), orgCommand.getAddress());
        Org tmp = orgRepository.save(org);
        return new OrgDto(tmp.getId(), tmp.getName(), tmp.getAddress());
    }

    @Transactional
    public OrgDto updateOrg(long id, OrgCommand orgCommand) {
        Org org2 = orgRepository.findById(id);
        if (Objects.isNull(org2)) {
            throw new CustomException(ExceptionResp.ORG_NOT_FOUND, "Org not found");
        }
        org2.setName(orgCommand.getName());
        org2.setAddress(orgCommand.getAddress());
        Org tmp = orgRepository.save(org2);
        return new OrgDto(tmp.getId(), tmp.getName(), tmp.getAddress());
    }
}
